const express = require('express')
let app = express()
const path = require("path")
const fs = require('fs')
let usersRoute = express.Router()
// 链接数据库
let model = require('../models/userModel')
// 使用md5组件加密密码
let md5 = require('md5')
let { returnData } = require("../util")

// 如果需要获取文件,就要使用外部插件
usersRoute.get("/getData", async (req, res) => {
    // let loginName
    // if (typeof req.query.loginName != "undefined") {
    //     loginName = req.query.loginName
    // }
    let resData = await model.find()
    //数据分页
    let maxConten = resData.length
    let paging = 3
    let pagingNum = Math.ceil(maxConten / paging)
    let nowPaging = req.query.p
    let backData = await model.find().skip((nowPaging - 1) * paging).limit(paging)
    resData = backData
    res.send({
        resData,
        pagingNum,
    })
});
usersRoute.post("/addUser", async (req, res) => {
    try {
        let reslut = await returnData(req)
        // 加密
        reslut.pwd = md5(reslut.pwd)
        // 创建时间戳
        reslut.time = new Date().toLocaleDateString()
        // 先根据密码和用户名删除掉重复项目
        // await model.deleteMany({ pwd: reslut.pwd })
        await model.create(reslut)
        res.json({ statu: 1 })
    } catch (error) {
        if (error) return console.log(error);
        res.json({ statu: 0 })
    }

})
// 创建删除路由
usersRoute.delete('/delUser', async (req, res) => {
    let { _id } = req.query
    // fs.rmSync()
    try {
        let { fileData } = await model.find({ _id })
        console.log(fileData);
        let reslut = await model.deleteOne({ _id })
        console.log(reslut);
        res.send({
            statu: 1
        })
    } catch (error) {
        console.log(error);
        res.send({
            statu: 0
        })
    }
});


module.exports = usersRoute